import tkinter as tk
from tkinter import messagebox, ttk
import hashlib
from tkinter import PhotoImage
# -*- coding: utf-8 -*-
# 导入库pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score  # 评价指标
import xgboost as xgb
import matplotlib.pyplot as plt
import warnings
import os
# 1（正常）
# 0.284654 -4.813031 0.266482 0.04374 0.02971 0.0313 0.426 0.02182 0.06545 2.301442
# 0.321749 -3.987214 0.298372 0.03298 0.04123 0.0279 0.398 0.03029 0.05874 2.287311
# 0.279832 -4.234987 0.253298 0.05123 0.03782 0.04012 0.412 0.02893 0.07123 2.321478
# 0.301298 -4.523789 0.274389 0.04789 0.03321 0.03567 0.409 0.02456 0.06893 2.298743

#0（不正常）
#-0.284654 4.813031 -0.266482 -0.04374 -0.02971 -0.0313 -0.426 -0.02182 -0.06545 -2.301442
#-0.301234 4.923456 -0.289372 -0.05123 -0.03456 -0.03789 -0.456 -0.02789 -0.07234 -2.401234
#-0.278932 4.789321 -0.259873 -0.04987 -0.02789 -0.02987 -0.432 -0.02345 -0.06987 -2.298732
users = {}
history_data = []


# 钓鱼url检测
def check_url(url):
    if url==0:
        return "非健康语音"
    else:
        return "健康语音"


# 密码加密函数
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()


# 登录功能
def login():
    username = entry_username.get()
    password = entry_password.get()
    hashed_password = hash_password(password)

    if username in users and users[username] == hashed_password:
        messagebox.showinfo("登录成功", f"欢迎回来, {username}")
        main_page()  # 跳转到主要页面
    else:
        messagebox.showerror("登录失败", "用户名或密码错误")


# 注册功能
def register():
    username = entry_username.get()
    password = entry_password.get()

    if username not in users:
        users[username] = hash_password(password)
        messagebox.showinfo("注册成功", "注册成功，请登录")
    else:
        messagebox.showwarning("注册失败", "用户名已存在")

model_path = "xgb_model.json"
# 加载保存的模型
xgb_model = xgb.XGBClassifier()
xgb_model.load_model(model_path)
print("模型已加载")
# 主要页面（输入网址进行分类识别）
def main_page():
    login_frame.pack_forget()  # 隐藏登录页面
    main_frame.pack(fill="both", expand=True)  # 显示主要页面


def classify_url():
    url = entry_url.get()
    url=url.split(' ')
    url=[float(i) for i in url]
    url=np.array(url).reshape(1,-1)
    y_pred = xgb_model.predict(url)
    print(y_pred)
    result = check_url(y_pred[0])

    history_data.append((url, result))
    label_result.config(text=f"识别结果: {result}")


# 历史查询页面
def history_page():
    main_frame.pack_forget()  # 隐藏主要页面
    history_frame.pack(fill="both", expand=True)  # 显示历史页面

    # 清空表格
    for row in tree.get_children():
        tree.delete(row)

    # 显示历史数据
    for index, (url, result) in enumerate(history_data):
        tree.insert("", "end", values=(index + 1, url, result))


# 返回主要页面
def back_to_main():
    history_frame.pack_forget()
    main_frame.pack(fill="both", expand=True)


# 创建一个美化的登录框架
def create_login_frame():
    global login_frame
    login_frame = tk.Frame(root, bg='#f0f0f0')
    login_frame.pack(fill="both", expand=True)

    # 背景图片（可以选择合适的背景图片路径）
    bg_image = PhotoImage(file="background.png")
    background_label = tk.Label(login_frame, image=bg_image)
    background_label.image = bg_image  # 避免图片被垃圾回收
    background_label.place(relwidth=1, relheight=1)

    login_box = tk.Frame(login_frame, bg='white', padx=10, pady=10)
    login_box.place(relx=0.5, rely=0.5, anchor='center')

    tk.Label(login_box, text="用户名:", font=("Helvetica", 12), bg='white').grid(row=0, column=0, pady=10)
    global entry_username
    entry_username = tk.Entry(login_box, font=("Helvetica", 12), width=20)
    entry_username.grid(row=0, column=1, pady=10)

    tk.Label(login_box, text="密码:", font=("Helvetica", 12), bg='white').grid(row=1, column=0, pady=10)
    global entry_password
    entry_password = tk.Entry(login_box, font=("Helvetica", 12), show="*", width=20)
    entry_password.grid(row=1, column=1, pady=10)

    login_button = tk.Button(login_box, text="登录", font=("Helvetica", 12), command=login, bg="#4CAF50", fg="white")
    login_button.grid(row=2, column=0, pady=10)

    register_button = tk.Button(login_box, text="注册", font=("Helvetica", 12), command=register, bg="#2196F3",
                                fg="white")
    register_button.grid(row=2, column=1, pady=10)


# 初始化主窗口
root = tk.Tk()
root.title("基于Transformer的语音识别系统")
root.geometry("500x500")

style = ttk.Style(root)
style.configure('TButton', font=('Helvetica', 12), padding=10)

# 创建登录页面
create_login_frame()

# 主要页面（分类识别）
main_frame = tk.Frame(root, bg='#ffffff')

label_welcome = tk.Label(main_frame, text="欢迎使用基于Transformer的语音识别系统", font=("Helvetica", 16), bg='#ffffff')
label_welcome.pack(pady=20)

entry_url = tk.Entry(main_frame, font=("Helvetica", 12), width=40)
entry_url.pack(pady=10)

classify_button = tk.Button(main_frame, text="分类识别", font=("Helvetica", 12), command=classify_url, bg="#4CAF50",
                            fg="white")
classify_button.pack(pady=10)

label_result = tk.Label(main_frame, text="分类结果:", font=("Helvetica", 14), bg='#ffffff')
label_result.pack(pady=10)

history_button = tk.Button(main_frame, text="历史查询", font=("Helvetica", 12), command=history_page, bg="#2196F3",
                           fg="white")
history_button.pack(pady=10)

# 历史查询页面
history_frame = tk.Frame(root, bg='#f0f0f0')

tk.Label(history_frame, text="历史查询记录:", font=("Helvetica", 16), bg='#f0f0f0').pack(pady=20)

columns = ("编号", "语音数据", "识别结果")
tree = ttk.Treeview(history_frame, columns=columns, show="headings", height=10)
tree.heading("编号", text="编号")
tree.heading("语音数据", text="语音数据")
tree.heading("识别结果", text="识别结果")
tree.pack(pady=10)

back_button = tk.Button(history_frame, text="返回", font=("Helvetica", 12), command=back_to_main, bg="#FF5722",
                        fg="white")
back_button.pack(pady=10)

# 启动主循环
root.mainloop()
